package com.qixia.upload.config;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

/**
 * @author: Sven
 * date: 2021/9/24 16:47
 * desc: API文档配置
 **/
@EnableOpenApi
@Configuration
public class Swagger3 {

    @Value("${swagger.host}")
    private String host;
    @Value("${swagger.show}")
    private boolean show;

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30).host(host).enable(show)
                .apiInfo(apiInfo())
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("文件上传服务")
                .description("文件上传，在线预览")
//                .contact(new Contact("Sven", "", "svenlast@dingtalk.com"))
                .contact(new Contact("", "", ""))
                .version("2.0")
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        return Collections.singletonList(HttpAuthenticationScheme.JWT_BEARER_BUILDER.name("Authorization").build());
    }

    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(SecurityContext.builder()
                .securityReferences(Collections.singletonList(SecurityReference.builder()
                        .scopes(new AuthorizationScope[0])
                        .reference("Authorization")
                        .build()))
                // 声明作用域
                .operationSelector(o -> o.requestMappingPattern().matches("/.*"))
                .build());
    }
}
